import Vue from 'vue';
import Vuex from 'vuex';
import { setToken, getToken, removeToken, getFundToken, setFundToken, removeFundToken } from '../utils/auth';
import { login, getUserInfo, fundLogin } from '../api/native';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    token: getToken(),
    fundToken: getFundToken(),
    user: {},
  },

  getters: {
    isLogin: state => Boolean(state.token),
   
    isFundLogin: state => Boolean(state.fundToken),
  },

  mutations: {
    SET_USER(state, user) {
      state.user = user;
    },

    SET_TOKEN(state, token) {
      state.token = token;
    },

    SET_FUND_TOKEN(state, token) {
      state.fundToken = token;
    },
  },

  actions: {
    async login({ commit }) {
      return login().then((data) => {
        if (data.token) {
          setToken(data.token);
          commit('SET_TOKEN', data.token);
        }
      });
    },

    async fundLogin({ commit }) {
      return fundLogin().then(((data) => {
        if (data.token) {
          setFundToken(data.token);
          commit('SET_FUND_TOKEN', data.token);
        }
      }));
    },

    async logout({ commit }) {
      commit('SET_TOKEN', '');
      removeToken();
    },

    async fundLogout({ commit }) {
      commit('SET_FUND_TOKEN', '');
      removeFundToken();
    },

    async getUserInfo({ commit }) {
      return getUserInfo().then((user) => {
        commit('SET_USER', user);
      });
    },
  },

});

export default store;
